#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "Scene.h"
#include "AddCommand.h"
#include "DeleteCommand.h"
#include "MoveCommand.h"

#include <QtGui/QRadioButton>
#include <QtGui/QSpinBox>
#include <QtGui/QGraphicsItem>
#include <QtGui/QUndoStack>
#include <QtGui/QUndoView>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    undoStack = new QUndoStack(this);

    undoView = new QUndoView(undoStack, ui->dockWidgetContents);
    ui->verticalLayout_2->addWidget(undoView);
    undoView->setFixedHeight(80);

    boxRadio = new QRadioButton("Box", this);
    boxRadio->setChecked(true);
    circleRadio = new QRadioButton("Circle", this);

    sizeSpin = new QSpinBox(this);
    sizeSpin->setMaximum(80);
    sizeSpin->setMinimum(50);

    ui->actionDelete->setEnabled(false);

    undoAction = undoStack->createUndoAction(this, "Undo");
    undoAction->setShortcut(QKeySequence::Undo);
    undoAction->setIcon(QIcon(":/Icons/Icons/undoIcon.png"));

    redoAction = undoStack->createRedoAction(this, "Redo");
    redoAction->setShortcut(QKeySequence::Redo);
    redoAction->setIcon(QIcon(":/Icons/Icons/redoIcon.png"));

    ui->mainToolBar->addWidget(boxRadio);
    ui->mainToolBar->addWidget(circleRadio);
    ui->mainToolBar->addWidget(sizeSpin);

    ui->mainToolBar->addSeparator();

    ui->mainToolBar->insertAction(ui->mainToolBar->addSeparator(), ui->actionDelete);

    ui->mainToolBar->insertAction(ui->mainToolBar->addSeparator(), redoAction);
    ui->mainToolBar->insertAction(redoAction, undoAction);

    scene = new Scene(QRectF(0, 0, 500, 600));
    ui->graphicsView->setScene(scene);

    QObject::connect(scene, SIGNAL(hasSelection(bool)), ui->actionDelete, SLOT(setEnabled(bool)));

    QObject::connect(scene, SIGNAL(mouseDoubleClick(QPointF)), this, SLOT(addItem(QPointF)));

    QObject::connect(ui->actionDelete, SIGNAL(triggered()), this, SLOT(deleteItem()));

    QObject::connect(scene, SIGNAL(itemMoved(QList<QGraphicsItem*>,QList<QPointF>)),
                     this, SLOT(itemMoved(QList<QGraphicsItem*>,QList<QPointF>)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::addItem(QPointF scenePos)
{
    bool itemType = true;
    if (boxRadio->isChecked() == false)
        itemType = false;

    undoStack->push(new AddCommand(itemType, sizeSpin->value(), scenePos, scene));
}

void MainWindow::deleteItem()
{
    undoStack->push(new DeleteCommand(scene));
}

void MainWindow::itemMoved(QList<QGraphicsItem *> item, QList<QPointF> oldPos)
{
    undoStack->push(new MoveCommand(item, oldPos));
}
